use chrono::NaiveDate;
use serde::{Deserialize, Deserializer};
use std::str::FromStr;

// 自定义反序列化模式-  数字或字符串
#[derive(Deserialize)]
#[serde(untagged)]
enum StringOrNumber<T> {
    String(String),
    Number(T),
}
pub fn deserialize_number<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
    T: Deserialize<'de> + FromStr,
    T::Err: std::fmt::Display,
    D: Deserializer<'de>,
{
    let wrapped_number = StringOrNumber::deserialize(deserializer)?;
    match wrapped_number {
        StringOrNumber::String(s) => s.parse::<T>().map_err(serde::de::Error::custom),
        StringOrNumber::Number(i) => Ok(i),
    }
}

pub fn deserialize_date<'de, D>(deserializer: D) -> Result<NaiveDate, D::Error>
where
    D: Deserializer<'de>,
{
    let date: String = Deserialize::deserialize(deserializer)?;
    //1. 尝试默认的 yyyy-MM-dd
    if let Ok(date) = NaiveDate::parse_from_str(&date, "%Y-%m-%d") {
        return Ok(date);
    }
    //2. 尝试yyyy/MM/dd格式
    if let Ok(date) = NaiveDate::parse_from_str(&date, "%Y/%m/%d") {
        return Ok(date);
    }
    //3. 最后尝试yyyyMMdd格式
    NaiveDate::parse_from_str(&date, "%Y%m%d").map_err(serde::de::Error::custom)
}